import { useQuery } from '@tanstack/react-query';
import { Space, Button, Input, Modal, Card, message } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';
import { ChargeModal } from '@/components/ChargeModal';
import { WithdrawModal } from '@/components/WithdrawModal';
import { toYuan } from '@/utils/format-number';

export default function WalletPage() {
  const [info, setInfo] = useState<any>({});
  const [show, setShow] = useState(false);
  const [params, setParams] = useState({ amount: 0, ticket: '', contact: '' });
  const [showPay, setShowPay] = useState(false);
  const [memberRechargeId, setMemberRechargeId] = useState('');
  const [query, setQuery] = useState<any>({});
  const [showDraw, setShowDraw] = useState(false);
  const tradeTypeMap: any = {
    1: '订单支付',
    2: '充值',
    3: '提现',
    5: '加价收益',
    6: '素材费收益',
    7: '推广收益',
    8: '提现驳回',
  };

  const inconeTypeMap: any = {
    1: '收入',
    2: '支出',
    3: '第三方支出',
  };
  // const [query, setQuery] = useState<any>({});
  useEffect(() => {
    commonService.getCustomApi('/member/myWallet', {}).then((res) => {
      setInfo(res || {});
    });
  }, []);

  // console.log(setQuery())

  const toPay = () => {
    const { amount } = params;
    if (!amount) {
      message.error('请选择或输入充值金额！');
      return false;
    }
    commonService
      .postCustomApi('/member/recharge/submitRecharge', { amount: (amount * 100).toFixed(0) })
      .then((res) => {
        setMemberRechargeId(res.id);
        setShowPay(true);
      });
  };

  const handleOk = () => {
    setShowPay(false);
  };

  const { data = {} } = useQuery({
    queryKey: ['/member/myAccountLogPage', query],
    queryFn: async () => {
      const params: any = {};
      Object.keys(query).forEach((key) => {
        if (query[key] || query[key] === 0) {
          params[key] = query[key];
        }
      });
      return commonService.getCustomApi('/member/myAccountLogPage', { ...params });
    },
  });

  const handleChange = (e: any) => {
    setQuery((prev: any) => ({
      ...prev,
      pageNo: e.current,
    }));
  };

  const columns: ColumnsType<any> = [
    { title: '会员ID', dataIndex: 'userId', width: 80 },
    { title: '交易号', dataIndex: 'tradeNo', align: 'center', width: 60 },
    {
      title: '交易类型',
      dataIndex: 'tradeType',
      align: 'center',
      width: 60,
      render: (val) => {
        return <div>{tradeTypeMap[val]}</div>;
      },
    },
    {
      title: '交易金额',
      dataIndex: 'tradeAmount',
      align: 'center',
      width: 60,
      render: (money) => <div>{toYuan(money)}元</div>,
    },
    {
      title: '收支类型',
      dataIndex: 'incomeFlag',
      align: 'center',
      width: 100,
      render: (val) => {
        return <div>{inconeTypeMap[val]}</div>;
      },
    },
    {
      title: '交易后余额',
      dataIndex: 'balance',
      align: 'center',
      width: 60,
      render: (money) => <div>{toYuan(money)}元</div>,
    },
    { title: '交易时间', dataIndex: 'tradeTime', align: 'center', width: 200 },
  ];

  return (
    <Space direction="vertical" size="large" className="ml-[60px] mt-[40px] w-full gap-[40px]">
      <div className="border-1 text-[24px]">我的钱包</div>
      <div className="flex">
        <div className="w-[200px]">
          余额：<span>{(info.balance / 100).toFixed(2)}</span>
        </div>
        <div className="flex gap-[10px]">
          <Button type="primary" onClick={() => setShow(true)} ghost>
            去充值
          </Button>
          <Button type="primary" ghost onClick={() => setShowDraw(true)}>
            去提现
          </Button>
        </div>
      </div>
      <Card title="资金流水">
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.totalCount }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data.list}
          onChange={handleChange}
        />
      </Card>
      <WithdrawModal show={showDraw} onClose={() => setShowDraw(false)} />
      <Modal open={show} okText="" cancelText="" onCancel={() => setShow(false)}>
        <div className="border-1 mb-[40px] text-[24px]">选择充值金额</div>
        {/* <Tabs
          activeKey={tab}
          onChange={(key) => setTab(key)}
          items={[
            { label: '线上充值', key: 'online' },
            { label: '银行转账(线下汇款)', key: 'offline' },
          ]}
        />
        {tab === 'online' ? ( */}
        <div className="flex flex-col gap-[20px]">
          <div className="flex gap-[20px]">
            <div>充值金额：</div>
            <Button
              type="primary"
              onClick={() => setParams({ ...params, amount: 100 })}
              ghost={params.amount !== 100}
            >
              100元
            </Button>
            <Button
              type="primary"
              onClick={() => setParams({ ...params, amount: 100 })}
              ghost={params.amount !== 3000}
            >
              3000元
            </Button>
            <Button
              type="primary"
              onClick={() => setParams({ ...params, amount: 100 })}
              ghost={params.amount !== 10000}
            >
              10000元
            </Button>
            <div className="w-[100px]">
              <Input
                onBlur={(e: any) => setParams({ ...params, amount: e.target.value })}
                placeholder="输入金额"
                suffix="元"
              />
            </div>
          </div>
          {/* <div>
              付款方式：
              <Button type="primary" onClick={() => setParams({ ...params, amount: 100 })} ghost>
                聚合支付
              </Button>
            </div> */}
          <div className="flex items-center">
            应付金额：
            <div className="text-[32px] text-[#FD7901]">{params.amount}元</div>
          </div>
          <div>
            <Button type="primary" onClick={toPay}>
              立即支付
            </Button>
          </div>
        </div>
        {/* ) : (
          <div className="flex flex-col gap-[20px]">
            <div>我司信息</div>
            <div className="border-1 w-[600px] leading-[50px]">
              <Row className="px-[20px]">
                <Col span="4">公司名称</Col>
                <Col span="12">浙江凯尚服务有限公司</Col>
              </Row>
              <Row className="bg-[#B3B5B9] px-[20px]">
                <Col span="4">银行名称</Col>
                <Col span="12">浙江工商银行</Col>
              </Row>
              <Row className="px-[20px]">
                <Col span="4">银行账号</Col>
                <Col span="12">9999 9999 9999 9999</Col>
              </Row>
              <Row className="bg-[#B3B5B9] px-[20px]">
                <Col span="4">开户银行</Col>
                <Col span="12">中国工商银行义乌支行</Col>
              </Row>
            </div>
            <div>汇款回执凭证(必填)：（请上传正常无翻转角度的截图，jpg、jpeg、png格式均可）</div>
            <div>
              <CommonUpload
                isSingle
                value={params.ticket}
                onChange={(e: any) => setParams({ ...params, ticket: e })}
              />
            </div>
            <div className="flex w-[800px]">
              请输入充值金额：
              <div className="mr-[20px] w-[100px]">
                <Input
                  value={params.amount}
                  onChange={(e: any) => setParams({ ...params, amount: e })}
                  suffix="元"
                />
              </div>
              联系方式
              <div className="w-[100px]">
                <Input
                  value={params.contact}
                  onChange={(e: any) => setParams({ ...params, contact: e })}
                />
              </div>
              <span className="text-[#686B73]">（建议留下您的手机号，方便我们与您及时联系）</span>
            </div>
            <div>
              <Button type="primary">提交</Button>
            </div>
          </div>
        )} */}
      </Modal>
      <ChargeModal
        show={showPay}
        onOk={handleOk}
        memberRechargeId={memberRechargeId}
        onClose={() => setShowPay(false)}
      />
    </Space>
  );
}
